package com.amumu.drama.common.commpont.notify;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.TypeReference;
import com.amumu.drama.common.config.NotifyConfig;
import com.amumu.drama.common.utils.json.JsonObjectUtils;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.ResourceLoader;

import java.util.Map;

/**
 * @author sunzhuang
 * @date 2024/10/25 10:22
 * @slogan 天下风云出我辈, 一入代码岁月催
 * @desc todo
 */

@Configuration
public class NotifyConfigLoader implements Ordered {
    private static final String APOLLO_NAMESPACE_COMMON = "susuwan.common";

    private static final String APOLLO_KEY_NOTIFIER = "log.custom.notify";

    private static final String APOLLO_KEY_NOTIFIER_TEMPLATE = "log.custom.notifyTemplate";

    public static NotifyConfig NOTIFY_CONFIG = new NotifyConfig();

    public static Map<String, String> NOTIFY_TEMPLATE = Maps.newHashMap();

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }

    public NotifyConfigLoader(ApplicationContext applicationContext, ResourceLoader resourceLoader) {
        String json = ConfigService.getConfig(APOLLO_NAMESPACE_COMMON).getProperty(APOLLO_KEY_NOTIFIER, null);
        if (StringUtils.isNotBlank(json)) {
            NotifyConfig nc = JsonObjectUtils.parseJson(json, NotifyConfig.class);
            resetNotifyConfig(nc);
        }
        String notifyTemplate = ConfigService.getConfig(APOLLO_NAMESPACE_COMMON).getProperty(APOLLO_KEY_NOTIFIER_TEMPLATE, null);
        restNotifyTemplate(notifyTemplate);
    }


    @Value("${log.custom.notifyTemplate:'{}'}")
    public void setNotifyTemplate(String notifyTemplate) {
        restNotifyTemplate(notifyTemplate);
    }

    @ApolloJsonValue("${log.custom.notify:}")
    public void setNotifyConfig(NotifyConfig val) {
        if (val != null) {
            NOTIFY_CONFIG = val;
            resetNotifyConfig(val);
        }
    }

    private void resetNotifyConfig(NotifyConfig nc) {
        if (nc == null) {
            return;
        }
        NOTIFY_CONFIG = nc;
        Notifier.initRobotGroupMap(nc);
    }

    private static void restNotifyTemplate(String notifyTemplate) {
        if (StringUtils.isNotBlank(notifyTemplate)) {
            NOTIFY_TEMPLATE.clear();
            Map<String, String> stringStringMap = JsonObjectUtils.parseJson(notifyTemplate, new TypeReference<Map<String, String>>() {
            });
            if (CollUtil.isNotEmpty(stringStringMap)) {
                NOTIFY_TEMPLATE.putAll(stringStringMap);
            }
        }
    }
}
